import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import TableDefined from '@/components/common/tableDefined'
import CleanFusion from '@/api/cleanFusion'
import { modalLayoutSm } from '@/config/layout'
import { Button, Input, Select, Modal, DatePicker, Form, Row, Col } from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import { MinusCircleOutlined, RightOutlined, PlusOutlined } from '@ant-design/icons';
import $axios from '@/utils/axios'; 
import moment from 'moment'
import Dynamic from '@/api/dynamic'
import { fn } from 'moment'
import './index.less'
const { Option } = Select;
const { RangePicker } = DatePicker;

const CleanRole: FC = () => {
  const tableRef: RefType = useRef()
  const AddMComRef: RefType = useRef()
  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      key: 'index',
      width: '80px',
      fixed: 'left',
      render: (text, record, index) => {
        return index + 1
      }
    },
    {
      title: '清洗规则名称',
      dataIndex: 'rule_name',
      key: 'rule_name',
    },
    {
      title: '参数',
      dataIndex: 'rule_param',
      key: 'rule_param',
    },
    {
      title: '录入人',
      dataIndex: 'person',
      key: 'person',
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      key: 'update_time',
      render: (text, record, index) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      title: '操作',
      dataIndex: 'scan',
      key: 'scan',
      width: '180px',
      render(txt, record, index) {
        return <div>
          <Button className="btn" onClick={() => edit(record.rule_id)} size="small">
            编辑
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => del(record.rule_id)} size="small">
            删除
          </Button>
        </div>
      }
    },
  ]
  const searchConfigList = [
    {
      key: 'keywords',
      slot: <Input placeholder="请输入关键字" allowClear />,
      rules: [],
      initialValue: ''
    },

    {
      key: 'date',
      slot: <RangePicker />,
      rules: [],
      initialValue: []
    },
  ];

  // 新增按钮
  const AddBtn = () => (

    <Button className="fr" onClick={add} type="primary">
      新增
    </Button>
  )
  // 批量删除
  const BatchDelBtn = () => (

    <Button style={{ marginRight: '15px' }} className="fr" onClick={del}>
      删除
    </Button>
  )
  // 添加
  const add = () => {
    AddMComRef.current.init()
  }
  // 添加
  const edit = (id) => {
    AddMComRef.current.init(id);
  }
  // 删除
  const del = (id: any) => {
    Modal.confirm({
      title: '确认删除？',

      onOk() {
        // Role.roleDel({
        //   roleid:record.roleid,
        //   isFormData:true
        // }).then(()=>{
        //   tableRef.current.update();
        // })
        Dynamic.DynamicExecute({
          apiID:'DMT_A001_03',
          apiParam:{
            rule_id:id
          }
        }).then((res)=>{
            window['ref1'].tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  return (
    <>
      <div>
        {/* <BatchDel /> */}

        <AddBtn />
        <BatchDelBtn />
      </div>


  <TableDefined
        apiFun={Dynamic.getDynamicQuery}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        extraProps={{ apiID: 'DMT_A001' }}
      />
      {/* <MyTable
        apiFun={CleanFusion.CleanRoleList}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        extraProps={{ results: 10 }}
        onSelectRow={(val) => {
          console.log(val);
        }}
        rowKey='id'
        beforeSearch={(val: any) => {
          // eslint-disable-next-line no-param-reassign
          console.log(val);
          if (val.date.length > 0) {
            val['st_time'] = val.date[0].format('YYYY-MM-DD');
            val['ed_time'] = val.date[1].format('YYYY-MM-DD');
          }
          // eslint-disable-next-line no-param-reassign
          return {}
        }}
      /> */}
      <AddMCom ref={AddMComRef} callback={() => {
        tableRef.current.update();
      }} />
    </>
  )
}
export default withRouter(CleanRole)

const AddM = (props, refs) => {

  const [form] = Form.useForm()
  const [id, setid] = useState('');
  const { setFieldsValue, resetFields } = form
  const [isModalVisible, setIsModalVisible] = useState(false);
  const typeValue = Form.useWatch('type', form);
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };


  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      console.log(Obj);

    }).catch(info => {

    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    resetFields();
    props.callback && props.callback();
  };
  useImperativeHandle(refs, () => ({
    init: (id) => {
      if (id) {
        setid(id);
        getDetail(id);
      } else {
        resetFields();
      }
      showModal();
      // setfileList([]);
    }
  }))
  const getDetail = (id) => {

  }
  return <Modal
    title={id === '' ? "新增" : '编辑'}
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    centered={true}
    width={540}
    maskClosable={false}
    bodyStyle={{
      maxHeight: window.innerHeight - 150,
      overflowY: 'auto'
    }}
  >
    <Form form={form} {...modalLayoutSm}>
      <Form.Item name='name' label="规则名称">
        <Input allowClear />
      </Form.Item>
      <Form.Item label='清洗方式' name='type'>
        <Select allowClear>
          {
            ['替换', '映射', '日期转文本', '大写转小写(字母)', '小写转大写(字母)', '左补全', '右补全', '去除空白', '去除左空白', '去除右空白', '全角转半角', '半角转全角', '正则替换'].map((e, i) => {
              return <Option value={i} key={i}>{e}</Option>
            })
          }
        </Select>
      </Form.Item>
      {
        [0, 1].indexOf(typeValue) != -1 && <Form.List
          name="params"

        >
          {(fields, { add, remove }, { errors }) => (
            <>
              <Form.Item label="参数">
                {fields.map((field, index) => (
                  <Row>
                    <Col span={10}>
                      <Form.Item name={[field.name, 'a']}>
                        <Input />
                      </Form.Item>
                    </Col>
                    <Col span={2}>
                      <div className='RightOutlinedWrap'>
                        <RightOutlined />
                      </div>

                    </Col>
                    <Col span={10}>
                      <Form.Item name={[field.name, 'b']}>
                        <Input />
                      </Form.Item>
                    </Col>
                  </Row>

                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    style={{ width: '60%' }}
                    icon={<PlusOutlined />}
                  >
                    添加参数
                  </Button>
                </Form.Item>
              </Form.Item>

            </>
          )}
        </Form.List>
      }
      {
        typeValue == 2 && <Form.Item label='日期类型' name='params' extra="年：YYYY  月：MM  日:DD 时:HH 分：mm 秒:SS">
          <Input placeholder='例：YYYY-MM-DD HH:mm:SS' />
        </Form.Item>
      }
        {
        typeValue == 12 && <Form.Item label='正则表达式' name='params' extra="">
          <Input />
        </Form.Item>
      }
      {/* <div>
        <pre>typeValue {typeValue}</pre>
      </div> */}
    </Form>
  </Modal>
}
const AddMCom = forwardRef(AddM);

